###############################################################################
# This is where all the R Magic happens, usually these routines are accessed via Java Callbacks
# 
#
# Copyright (c) 2009 Daniel Kornhauser.  All rights reserved.
# Author: Daniel Kornhauser
###############################################################################

my.dat = NULL # Data Frame that contains acumulates dataset each time the user executes the model or load a csv file
my.new_dat = NULL # Last loaded data frame
my.partial_dat = NULL
my.viz = NULL # R Graphic Object that will be rendered in Java Graphics Device
my.colors =  NULL# Colors Pallette made from color brewer  
my.transparency = 1
my.scale = "same"

##########################
### AUXILIARY FUNCTIONS ####
##########################

### print function that can be easely disabled
print_debug <- function (...) 
{	
	## <- list(...) # Put the arguments in a (named) list
	##for (i in seq(along = l)) 
	##{
	##	cat("Argument ", i, " name:", names(l)[i], "Value:", l[[i]], "\n")		   
	##}
}

############
### INIT #####
############

# Load libraries and set environement variables.
init_r <- function () 
{
	source("interaction-modified.R")
	
	library(JavaGD)
	library(grid)   
	library(lattice)    
	library(latticeExtra)
	library(reshape)
	
	Sys.setenv('JAVAGD_CLASS_NAME'='GD')
	JavaGD()
	init_viz()
}

# Load the data from a csv file
load_dat <- function (filename, dataset_num)
{
	print(c("################", dataset_num))
	my.new_dat <<- read.csv(filename, skip=6, header = TRUE)
	my.new_dat <<-data.frame(dataset = dataset_num, my.new_dat)
	if (! is.null(my.dat)) # Usual case, our file contains data
	{
		my.dat  <<-  merge_all(list(my.new_dat, my.dat ))
	}
	else # Only happens if the dataset is empty
	{
		##print(c("------------------", my.new_dat))
		my.dat <<- my.new_dat
	}
}

# Load the data from a csv file
load_incomplete_dat <- function (filename, dataset_num)
{
	print("------> 1 LOADING DATA !!!")
	my.selected_dat  <<- read.csv(filename, skip=6, header = TRUE)
	my.selected_dat <<-data.frame(dataset = 1, my.selected_dat)
	print(str(my.selected_dat ))
	print("------> 2 LOADING DATA !!!")
}

# Get the summary for the dataframe to display in GUI
get_dataset_summary <- function (dataset_num) 
{
	print(c("*************************", dataset_num))
	my.selected_dataset <- subset(my.dat, dataset %in% c(dataset_num) )
	summary_dataset <- summary(my.selected_dataset)
	sum_dataset <- format(summary_dataset,width=150)
	return(capture.output(sum_dataset))
}

# Get the summary for the dataframe to display in GUI
get_dataset_str<- function (dataset_num) 
{
	my.selected_dataset <- subset(my.dat, dataset %in% c(dataset_num) )
	return(capture.output(str(my.selected_dataset)))
}

# Allows us to select only a few datasets
subset_dataset <- function(chosen_dataset_nums) {
	print("***** subset *****")
	# selecting datasets that are not selected
	my.selected_dat <<- subset(my.dat, dataset %in% chosen_dataset_nums)
	dataset_levels <<-  levels(factor(my.selected_dat$dataset))
	
}

#Assigns the exact number of colors necesary for the scheme
assign_colors <- function(palette_name, data_frame)
{
	#TODO change the 9 by maximum number of color in palette
	dataset_length =  length(unique(data_frame))
	# For brewer.pal  minimal value for n is 3 so we have to truncate.
	if (dataset_length == 1)
	{ my.colors <<- brewer.pal(3, palette_name)[1] }
	else if (dataset_length == 2)
	{ my.colors <<- brewer.pal(3, palette_name)[1:2] }
	else if (dataset_length > 2 & dataset_length < 9 )
	{ my.colors <<- brewer.pal(dataset_length, palette_name) }
	else if (dataset_length > 9 )
	{ my.colors <<- brewer.pal(9, palette_name) }
}

# Allows us to further filter the data to be ploted with a custom expression from an GUI entry
subset_custom <- function(keep) {
	keep_parsed = parse(text=keep)
	my.selected_dat <<- subset(my.selected_dat,eval(keep_parsed) )
	summary(my.selected_dat)
}

#########
#PLOT_VIZ#
#########

# TODO Check how to modify the templay
init_viz <-function()
{
	trellis.par.set( axis.line = list(lwd=1) )
	trellis.par.set(strip.border = list(col="black"))
	trellis.par.set(legend.bbox = "panel")	
	#trellis.par.set(border = TRUE)
	#trellis.par.set(layout.widths=list(left.padding=0, right.padding=20))
	#trellis.par.set(layout.heights=list(top.padding=0, bottom.padding=0))
}

set_manual_options<-function(transparency, free_scales)
{
	my.transparency <<- as.numeric(transparency) / 100
	
	if (free_scales == 'true') 
	{my.scale <<- "free"}
	else 
	{my.scale <<-"same"}
}

set_automatic_options<-function(xName , yName, groupName )
{
	if ( xName == 'X.step.' || xName == 'X.step.' )
	{
		my.type <<-'l'
		my.pch <<- '+'
	}
	else
	{
		my.type <<-'p'
		my.pch <<- '.'
	}
	
	if (nchar(groupName) < 8) {	my.cex.title <<- 1 }
	else if (nchar(groupName) > 8) {	my.cex.title <<- (nchar(groupName) - (nchar(groupName)/3))/nchar(groupName) }

	group_parsed = parse(text = paste('my.selected_dat$',groupName, sep=''))
	
	
	my.groups <<- interaction(eval(group_parsed), my.selected_dat$X.run.number.)
	
	my.key <<- list( 
			title =  groupName,
			cex.title = my.cex.title ,
			space="right",
			text =  list( levels(factor(eval(group_parsed)))), 
			lines = list(col = my.colors))
}

##############
### XY PLOTS ###
##############

####plot_viz####
plot_viz <- function(xName, yName, condXName, condYName, groupName, heatmap) 
{
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	lattice.options(par.settings = list(border = TRUE),
			(layout.widths=list(left.padding=0, right.padding=20)),
			(layout.heights=list(top.padding=0, bottom.padding=0)))
	set_automatic_options(xName, yName,  groupName)
	print_debug('1 Make syntactically valid names')
	xName = make.names(xName)
	yName = make.names(yName)
	condXName = make.names(condXName)
	condYName = make.names(condYName)
	if (nchar(heatmap) == 0) {heatmap = "1"}
	print_debug (c(xName, yName, condXName, condYName))
	
	print_debug('2 Extract column with names from my.selected_dat')
	x  <-  my.selected_dat[[xName]]
	y  <-  my.selected_dat[[yName]]	
	condX = my.selected_dat[[condXName]]
	condY = my.selected_dat[[condYName]]
	
	print_debug('3 Parse groupName and heatmap')
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}	
	heatmap_parsed = parse(text = heatmap)	
	print_debug('4 plot_viz xyplot')
	
	print(c("------------------->",my.transparency ))
   
	
	v =	xyplot(y ~ x |  factor(condX) + factor(condY) ,
			data = my.selected_dat,
			groups = my.groups,
			scales = my.scale ,
			alpha = 	my.transparency,
			type = my.type,
			pch = my.pch,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' - ',
					bg = 'white',
					fg = 'white'),
			col = my.colors,
			main = paste(yName, xName, sep=' vs. '),
			xlab = condXName,
			ylab = condYName,	
			aspect = "fill",
			key =  my.key,
			aux.env = new.env(parent = emptyenv()),
			# prepanel calculates the heatmap.max to normalize the heatmap gray shade from 0 to 1
			prepanel = function(x, y, aux.env, ...) 
			{
				y <- na.exclude(y)
				x <- na.exclude(x)
				print_debug(c("eval(heatmap_parsed) ==>",eval(heatmap_parsed) ))
				if (!is.na(eval(heatmap_parsed)) & is.na(as.numeric(heatmap)))
				{
					aux.env$heatmap.max <- max(aux.env$heatmap.max, eval(heatmap_parsed), na.rm = TRUE)
				}
				else if ( ! is.na(as.numeric(heatmap)))
				{
					aux.env$heatmap.max <- 1					
				}
				list()
			},
			panel = function(x, y, subscripts, aux.env, ...) 
			{	
				# Filter na from x and y at each panel so they are not taken in account in eval(heatmap_parsed)
				na_x = which(!is.na(x))
				y <- y[na_x]
				x <- x[na_x]
				subscripts <- subscripts[na_x]
				na_y = which(!is.na(y))
				y <- y[na_y]
				x <- x[na_y]
				subscripts <- subscripts[na_y]
				
				#TODO: fail gracefully with invalid statements  
				eval_heatmap = eval(heatmap_parsed) / aux.env$heatmap.max
				
				# Put gray squares  if NaN
				if (!is.na(eval_heatmap) )
				{panel.fill(col = rgb(eval_heatmap,eval_heatmap,eval_heatmap))}
				else
				{panel.grid(col = "gray", lty = 1)}
				
				# The most important fuction responsable for drawing the lines
				panel.superpose(x, y, subscripts, ...)
			}
	)
		
	print_debug('5 useOuterStrips')	
	v = useOuterStrips( v,
			strip.left = strip.custom(
					strip.levels = TRUE, 
					strip.names = FALSE, 
					sep = ' - ',
					bg = 'white', 
					fg = 'white'
			), 
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' - ',
					bg = 'white',
					fg = 'white'
			),
	)
	
	print(v)
	viz <<- v
}

####plot_viz_x#####
plot_viz_x <- function(xName, yName, condXName, groupName, heatmap)
{
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	set_automatic_options(xName, yName,  groupName)
	print_debug('1 Make syntactically valid names')
	xName = make.names(xName)
	yName = make.names(yName)
	condXName = make.names(condXName)
	print_debug ("c(nchar(heatmap) ",nchar(heatmap))
	if (nchar(heatmap) == 0) 
	{
		heatmap = "1"
	}
	
	print_debug('2 Extract column with names from my.selected_dat')
	x  <-  my.selected_dat[[xName]]
	y  <-  my.selected_dat[[yName]]	
	condX = my.selected_dat[[condXName]]
	
	print_debug('3 Parse groupName and heatmap')
	heatmap_parsed = parse(text = heatmap)	
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}
	
	print_debug('4 plot_viz_x xyplot')	
	v =	xyplot(y ~ x | factor(condX),
			data = my.selected_dat,
			groups = 	my.groups,
			scales = my.scale ,
			alpha = my.transparency,
			type = my.type,
			pch = my.pch,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' * ',
					bg = 'white',
					fg = 'white'),
			col = my.colors,
			xlab = condXName,
			ylab = xName,
			main = yName,
			# TODO: Fix the layout so it produces a vertical line of plots with the correct length
			#aspect =eval(parse(text=c("nlevels(shingle(my.dat$",condXName,"))")))/2,
			#layout = c(0,eval(parse(text=c("nlevels(shingle(my.dat$",condXName,"))")))),
			key = 	my.key,
			aux.env = new.env(parent = emptyenv()),
			prepanel = function(x, y, aux.env, ...) 
			{
				y <- na.exclude(y)
				x <- na.exclude(x)
				print_debug(c("eval(heatmap_parsed) ==>",eval(heatmap_parsed) ))
				if (!is.na(eval(heatmap_parsed)))
				{
					aux.env$heatmap.max <- max(aux.env$heatmap.max, eval(heatmap_parsed), na.rm = TRUE)
				}
				list()
			},
			panel = function(x, y, subscripts, aux.env, ...) 
			{	
				# Filter na from x and y at each panel so they are not taken in account in eval(heatmap_parsed)
				na_x = which(!is.na(x))
				y <- y[na_x]
				x <- x[na_x]
				subscripts <- subscripts[na_x]
				na_y = which(!is.na(y))
				y <- y[na_y]
				x <- x[na_y]
				subscripts <- subscripts[na_y]
				
				#TODO: fail gracefully with invalid statements  
				eval_heatmap = eval(heatmap_parsed) / aux.env$heatmap.max
				
				# Put gray squares  if NaN
				if (!is.na(eval_heatmap) )
				{panel.fill(col = rgb(eval_heatmap,eval_heatmap,eval_heatmap))}
				else
				{panel.grid(col = "gray", lty = 1)}
				
				# The most important fuction responsable for drawing the lines
				panel.superpose(x, y, subscripts, ...)
			}
	)
	print(v)
	my.viz <<- v
}

####plot_viz_superposed####
plot_viz_superposed <- function(xName, yName, groupName) 
{
	print(groupName)
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	set_automatic_options(xName, yName,  groupName)
	print_debug('1 Make syntactically valid names')
	xName = make.names(xName)
	yName = make.names(yName)
	
	print_debug('2 Extract column with names from my.selected_dat')
	x  <-  my.selected_dat[[xName]]
	y  <-  my.selected_dat[[yName]]	
	
	print_debug('3 Parse groupName and heatmap')
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}
	
	print_debug('3 plot_viz_superposed xyplot')	
	v =	xyplot(y ~ x,
			data = my.selected_dat,
			groups = 	my.groups,
			scales = my.scale,
			alpha = my.transparency,
			type = my.type,
			pch = my.pch,
			col = my.colors,
			key = 	my.key,
			aspect = "fill")
	print(v)
	my.viz <<- v
}

#################
### HISTOGRAMS ###
#################

####plot_viz histogram####
plot_viz_histogram <- function(yName, condXName, condYName, groupName, heatmap) 
{
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	lattice.options(par.settings = list(border = TRUE),
			(layout.widths=list(left.padding=0, right.padding=20)),
			(layout.heights=list(top.padding=0, bottom.padding=0)))
	#TODO: update function below to only receive yName
    ##set_automatic_options(xName, yName,  groupName)
	print('1 Make syntactically valid names')
	yName = make.names(yName)
	condX = my.selected_dat[[condXName]]
	condY = my.selected_dat[[condYName]]

	if (nchar(heatmap) == 0) {heatmap = "1"}
	print_debug (c(xName, yName,  condYName))
	
	print('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	condY = my.selected_dat[[condYName]]
	
	print('3 Parse groupName and heatmap')
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}	
	heatmap_parsed = parse(text = heatmap)	
	print_debug('4 plot_viz xyplot')
	
	print(c("------------------->",str(y) ))
	
	v =	histogram(~ y |  factor(condX) + factor(condY) ,
			data = my.selected_dat,
			groups = 	my.groups ,
			scales = my.scale ,
			alpha = 	my.transparency,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' - ',
					bg = 'white',
					fg = 'white'),
			col = my.colors,
			xlab = condXName,
			ylab = condYName,
			aspect = "fill",
			main = yName,
			key = my.key ,
			aux.env = new.env(parent = emptyenv()),
			# prepanel calculates the heatmap.max to normalize the heatmap gray shade from 0 to 1
#			prepanel = function(x, y, aux.env, ...) 
#			{
#				y <- na.exclude(y)
#				x <- na.exclude(x)
#				print_debug(c("eval(heatmap_parsed) ==>",eval(heatmap_parsed) ))
#				if (!is.na(eval(heatmap_parsed)) & is.na(as.numeric(heatmap)))
#				{
#					aux.env$heatmap.max <- max(aux.env$heatmap.max, eval(heatmap_parsed), na.rm = TRUE)
#				}
#				else if ( ! is.na(as.numeric(heatmap)))
#				{
#					aux.env$heatmap.max <- 1					
#				}
#				list()
#			},
#			panel = function(x, y, subscripts, aux.env, ...) 
#			{	
#				# Filter na from x and y at each panel so they are not taken in account in eval(heatmap_parsed)
#				na_x = which(!is.na(x))
#				y <- y[na_x]
#				x <- x[na_x]
#				subscripts <- subscripts[na_x]
#				na_y = which(!is.na(y))
#				y <- y[na_y]
#				x <- x[na_y]
#				subscripts <- subscripts[na_y]
#				
#				#TODO: fail gracefully with invalid statements  
#				eval_heatmap = eval(heatmap_parsed) / aux.env$heatmap.max
#				
#				# Put gray squares  if NaN
#				if (!is.na(eval_heatmap) )
#				{panel.fill(col = rgb(eval_heatmap,eval_heatmap,eval_heatmap))}
#				else
#				{panel.grid(col = "gray", lty = 1)}
#				
#				# The most important fuction responsable for drawing the lines
#				panel.superpose(x, y, subscripts, ...)
#			}
	)
	
	print_debug('5 useOuterStrips')	
	v = useOuterStrips( v,
			strip.left = strip.custom(
					strip.levels = TRUE, 
					strip.names = FALSE, 
					sep = ' - ',
					bg = 'white', 
					fg = 'white'
			), 
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' - ',
					bg = 'white',
					fg = 'white'
			),
	)
	
	print(v)
	viz <<- v
}

####plot_viz_histogram#####
plot_viz_x_histogram<- function( yName, condXName, groupName, heatmap)
{
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	print_debug('1 Make syntactically valid names')
	yName = make.names(yName)
	condXName = make.names(condXName)
	print_debug ("c(nchar(heatmap) ",nchar(heatmap))
	if (nchar(heatmap) == 0) 
	{
		heatmap = "1"
	}
	
	print_debug('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	condX = my.selected_dat[[condXName]]
	
	print_debug('3 Parse groupName and heatmap')
	heatmap_parsed = parse(text = heatmap)	
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}
	
	print_debug('4 plot_viz_x xyplot')	
	v =	histogram(~ y | factor(condX),
			data = my.selected_dat,
			groups = 	my.groups ,
			scales = my.scale ,
			alpha = my.transparency,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' * ',
					bg = 'white',
					fg = 'white'),
			col = my.colors,
			xlab = condXName,
			main = yName,
			# TODO: Fix the layout so it produces a vertical line of plots with the correct length
			#aspect =eval(parse(text=c("nlevels(shingle(my.dat$",condXName,"))")))/2,
			#layout = c(0,eval(parse(text=c("nlevels(shingle(my.dat$",condXName,"))")))),
			key = 	my.key,
			aux.env = new.env(parent = emptyenv()),
#			prepanel = function(x, y, aux.env, ...) 
#			{
#				y <- na.exclude(y)
#				x <- na.exclude(x)
#				print_debug(c("eval(heatmap_parsed) ==>",eval(heatmap_parsed) ))
#				if (!is.na(eval(heatmap_parsed)))
#				{
#					aux.env$heatmap.max <- max(aux.env$heatmap.max, eval(heatmap_parsed), na.rm = TRUE)
#				}
#				list()
#			},
#			panel = function(x, y, subscripts, aux.env, ...) 
#			{	
#				# Filter na from x and y at each panel so they are not taken in account in eval(heatmap_parsed)
#				na_x = which(!is.na(x))
#				y <- y[na_x]
#				x <- x[na_x]
#				subscripts <- subscripts[na_x]
#				na_y = which(!is.na(y))
#				y <- y[na_y]
#				x <- x[na_y]
#				subscripts <- subscripts[na_y]
#				
#				#TODO: fail gracefully with invalid statements  
#				eval_heatmap = eval(heatmap_parsed) / aux.env$heatmap.max
#				
#				# Put gray squares  if NaN
#				if (!is.na(eval_heatmap) )
#				{panel.fill(col = rgb(eval_heatmap,eval_heatmap,eval_heatmap))}
#				else
#				{panel.grid(col = "gray", lty = 1)}
#				
#				# The most important fuction responsable for drawing the lines
#				panel.superpose(x, y, subscripts, ...)
#			}
	)
	print(v)
	my.viz <<- v
}

####plot_viz_superposed_histogram####
plot_viz_superposed_histogram <- function( yName, groupName) 
{
	print(groupName)
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	print_debug('1 Make syntactically valid names')
	yName = make.names(yName)
	
	print_debug('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	
	print_debug('3 Parse groupName and heatmap')
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}
	
	print_debug('3 plot_viz_superposed xyplot')	
	v =	histogram(~ y,
			data = my.selected_dat,
			groups = 	my.groups,
			scales = my.scale,
			alpha = my.transparency,
			col = my.colors,
			key = 	my.key ,
			aspect = "fill")
	print(v)
	my.viz <<- v
}

####plot_viz_splom####
plot_viz_splom_names<- function(checked_column_names)
{
	assign_colors("Pastel1", my.selected_dat$X.run.number.)
	print(checked_column_names)
	print(str(my.selected_dat))
	print(str(subset(my.selected_dat,select = checked_column_names)))
	v = splom(subset(my.selected_dat,select = checked_column_names),  
			pch = '.',  
			col = my.colors,
			alpha = my.transparency, 
			scale = my.scale ,  
			groups = my.selected_dat$X.run.number.
	)
	print(v)
	my.viz <<- v
	print(my.colors)
}


##################
### DENSITY PLOT ###
##################

####plot_viz densityplot####
plot_viz_densityplot <- function(yName, condXName, condYName, groupName, heatmap) 
{
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	lattice.options(par.settings = list(border = TRUE),
			(layout.widths=list(left.padding=0, right.padding=20)),
			(layout.heights=list(top.padding=0, bottom.padding=0)))
	#TODO: update function below to only receive yName
	##set_automatic_options(xName, yName,  groupName)
	print('1 Make syntactically valid names')
	yName = make.names(yName)
	condX = my.selected_dat[[condXName]]
	condY = my.selected_dat[[condYName]]
	
	if (nchar(heatmap) == 0) {heatmap = "1"}
	print_debug (c(xName, yName,  condYName))
	
	print('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	condY = my.selected_dat[[condYName]]
	
	print('3 Parse groupName and heatmap')
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}	
	heatmap_parsed = parse(text = heatmap)	
	print_debug('4 plot_viz xyplot')
	
	print(c("------------------->",str(y) ))
	
	v =	densityplot(~ y |  factor(condX) + factor(condY) ,
			data = my.selected_dat,
			groups = 	my.groups ,
			scales = my.scale ,
			alpha = 	my.transparency,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' - ',
					bg = 'white',
					fg = 'white'),
			col = my.colors,
			xlab = condXName,
			ylab = condYName,
			aspect = "fill",
			main = yName,
			key = 	my.key ,
			aux.env = new.env(parent = emptyenv()),
	# prepanel calculates the heatmap.max to normalize the heatmap gray shade from 0 to 1
#			prepanel = function(x, y, aux.env, ...) 
#			{
#				y <- na.exclude(y)
#				x <- na.exclude(x)
#				print_debug(c("eval(heatmap_parsed) ==>",eval(heatmap_parsed) ))
#				if (!is.na(eval(heatmap_parsed)) & is.na(as.numeric(heatmap)))
#				{
#					aux.env$heatmap.max <- max(aux.env$heatmap.max, eval(heatmap_parsed), na.rm = TRUE)
#				}
#				else if ( ! is.na(as.numeric(heatmap)))
#				{
#					aux.env$heatmap.max <- 1					
#				}
#				list()
#			},
#			panel = function(x, y, subscripts, aux.env, ...) 
#			{	
#				# Filter na from x and y at each panel so they are not taken in account in eval(heatmap_parsed)
#				na_x = which(!is.na(x))
#				y <- y[na_x]
#				x <- x[na_x]
#				subscripts <- subscripts[na_x]
#				na_y = which(!is.na(y))
#				y <- y[na_y]
#				x <- x[na_y]
#				subscripts <- subscripts[na_y]
#				
#				#TODO: fail gracefully with invalid statements  
#				eval_heatmap = eval(heatmap_parsed) / aux.env$heatmap.max
#				
#				# Put gray squares  if NaN
#				if (!is.na(eval_heatmap) )
#				{panel.fill(col = rgb(eval_heatmap,eval_heatmap,eval_heatmap))}
#				else
#				{panel.grid(col = "gray", lty = 1)}
#				
#				# The most important fuction responsable for drawing the lines
#				panel.superpose(x, y, subscripts, ...)
#			}
	)
	
	print_debug('5 useOuterStrips')	
	v = useOuterStrips( v,
			strip.left = strip.custom(
					strip.levels = TRUE, 
					strip.names = FALSE, 
					sep = ' - ',
					bg = 'white', 
					fg = 'white'
			), 
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' - ',
					bg = 'white',
					fg = 'white'
			),
	)
	
	print(v)
	viz <<- v
}

####plot_viz_densityplot#####
plot_viz_x_denistyplot<- function( yName, condXName, groupName, heatmap)
{
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	print_debug('1 Make syntactically valid names')
	yName = make.names(yName)
	condXName = make.names(condXName)
	print_debug ("c(nchar(heatmap) ",nchar(heatmap))
	if (nchar(heatmap) == 0) 
	{
		heatmap = "1"
	}
	
	print_debug('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	condX = my.selected_dat[[condXName]]
	
	print_debug('3 Parse groupName and heatmap')
	heatmap_parsed = parse(text = heatmap)	
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}
	
	print_debug('4 plot_viz_x xyplot')	
	v =	densityplot(~ y | factor(condX),
			data = my.selected_dat,
			groups = 	my.groups ,
			scales = my.scale ,
			alpha = my.transparency,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' * ',
					bg = 'white',
					fg = 'white'),
			col = my.colors,
			xlab = condXName,
			main = yName,
			# TODO: Fix the layout so it produces a vertical line of plots with the correct length
			#aspect =eval(parse(text=c("nlevels(shingle(my.dat$",condXName,"))")))/2,
			#layout = c(0,eval(parse(text=c("nlevels(shingle(my.dat$",condXName,"))")))),
			key = my.key ,
			aux.env = new.env(parent = emptyenv()),
#			prepanel = function(x, y, aux.env, ...) 
#			{
#				y <- na.exclude(y)
#				x <- na.exclude(x)
#				print_debug(c("eval(heatmap_parsed) ==>",eval(heatmap_parsed) ))
#				if (!is.na(eval(heatmap_parsed)))
#				{
#					aux.env$heatmap.max <- max(aux.env$heatmap.max, eval(heatmap_parsed), na.rm = TRUE)
#				}
#				list()
#			},
#			panel = function(x, y, subscripts, aux.env, ...) 
#			{	
#				# Filter na from x and y at each panel so they are not taken in account in eval(heatmap_parsed)
#				na_x = which(!is.na(x))
#				y <- y[na_x]
#				x <- x[na_x]
#				subscripts <- subscripts[na_x]
#				na_y = which(!is.na(y))
#				y <- y[na_y]
#				x <- x[na_y]
#				subscripts <- subscripts[na_y]
#				
#				#TODO: fail gracefully with invalid statements  
#				eval_heatmap = eval(heatmap_parsed) / aux.env$heatmap.max
#				
#				# Put gray squares  if NaN
#				if (!is.na(eval_heatmap) )
#				{panel.fill(col = rgb(eval_heatmap,eval_heatmap,eval_heatmap))}
#				else
#				{panel.grid(col = "gray", lty = 1)}
#				
#				# The most important fuction responsable for drawing the lines
#				panel.superpose(x, y, subscripts, ...)
#			}
	)
	print(v)
	my.viz <<- v
}

####plot_viz_superposed_densityplot####
plot_viz_superposed_densityplot <- function( yName, groupName) 
{
	print(groupName)
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	print_debug('1 Make syntactically valid names')
	yName = make.names(yName)
	
	print_debug('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	
	print_debug('3 Parse groupName and heatmap')
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}
	
	print_debug('3 plot_viz_superposed xyplot')	
	v =	densityplot(~ y,
			data = my.selected_dat,
			groups = my.groups ,
			scales = my.scale,
			alpha = my.transparency,
			col = my.colors,
			key = my.key ,
			aspect = "fill")
	print(v)
	my.viz <<- v
}


######################
### BOX WHISKER PLOT  ###
######################

####plot_viz densityplot####
plot_viz_bwplot <- function(yName, condXName, condYName, groupName, heatmap) 
{
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	lattice.options(par.settings = list(border = TRUE),
			(layout.widths=list(left.padding=0, right.padding=20)),
			(layout.heights=list(top.padding=0, bottom.padding=0)))
	#TODO: update function below to only receive yName
	##set_automatic_options(xName, yName,  groupName)
	print('1 Make syntactically valid names')
	yName = make.names(yName)
	condX = my.selected_dat[[condXName]]
	condY = my.selected_dat[[condYName]]
	
	if (nchar(heatmap) == 0) {heatmap = "1"}
	print_debug (c(xName, yName,  condYName))
	
	print('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	condY = my.selected_dat[[condYName]]
	
	print('3 Parse groupName and heatmap')
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}	
	heatmap_parsed = parse(text = heatmap)	
	print_debug('4 plot_viz xyplot')
	
	print(c("------------------->",str(y) ))
	
	v =	bwplot(interaction(eval(group_parsed), X.run.number.) ~ y |  factor(condX) + factor(condY) ,
			data = my.selected_dat,
			groups =	my.groups,
			scales = my.scale ,
			alpha = 	my.transparency,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' - ',
					bg = 'white',
					fg = 'white'),
			col = my.colors,
			xlab = condXName,
			ylab = condYName,
			aspect = "fill",
			main = yName,
			key = 	my.key,
			aux.env = new.env(parent = emptyenv()),
	# prepanel calculates the heatmap.max to normalize the heatmap gray shade from 0 to 1
#			prepanel = function(x, y, aux.env, ...) 
#			{
#				y <- na.exclude(y)
#				x <- na.exclude(x)
#				print_debug(c("eval(heatmap_parsed) ==>",eval(heatmap_parsed) ))
#				if (!is.na(eval(heatmap_parsed)) & is.na(as.numeric(heatmap)))
#				{
#					aux.env$heatmap.max <- max(aux.env$heatmap.max, eval(heatmap_parsed), na.rm = TRUE)
#				}
#				else if ( ! is.na(as.numeric(heatmap)))
#				{
#					aux.env$heatmap.max <- 1					
#				}
#				list()
#			},
#			panel = function(x, y, subscripts, aux.env, ...) 
#			{	
#				# Filter na from x and y at each panel so they are not taken in account in eval(heatmap_parsed)
#				na_x = which(!is.na(x))
#				y <- y[na_x]
#				x <- x[na_x]
#				subscripts <- subscripts[na_x]
#				na_y = which(!is.na(y))
#				y <- y[na_y]
#				x <- x[na_y]
#				subscripts <- subscripts[na_y]
#				
#				#TODO: fail gracefully with invalid statements  
#				eval_heatmap = eval(heatmap_parsed) / aux.env$heatmap.max
#				
#				# Put gray squares  if NaN
#				if (!is.na(eval_heatmap) )
#				{panel.fill(col = rgb(eval_heatmap,eval_heatmap,eval_heatmap))}
#				else
#				{panel.grid(col = "gray", lty = 1)}
#				
#				# The most important fuction responsable for drawing the lines
#				panel.superpose(x, y, subscripts, ...)
#			}
	)
	
	print_debug('5 useOuterStrips')	
	v = useOuterStrips( v,
			strip.left = strip.custom(
					strip.levels = TRUE, 
					strip.names = FALSE, 
					sep = ' - ',
					bg = 'white', 
					fg = 'white'
			), 
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' - ',
					bg = 'white',
					fg = 'white'
			),
	)
	
	print(v)
	viz <<- v
}

####plot_viz_densityplot#####
plot_viz_x_bwplot<- function( yName, condXName, groupName, heatmap)
{
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	print_debug('1 Make syntactically valid names')
	yName = make.names(yName)
	condXName = make.names(condXName)
	print_debug ("c(nchar(heatmap) ",nchar(heatmap))
	if (nchar(heatmap) == 0) 
	{
		heatmap = "1"
	}
	
	print_debug('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	condX = my.selected_dat[[condXName]]
	
	print_debug('3 Parse groupName and heatmap')
	heatmap_parsed = parse(text = heatmap)	
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}
	
	print_debug('4 plot_viz_x xyplot')	
	v =	bwplot(interaction(eval(group_parsed), X.run.number.) ~ y | factor(condX),
			data = my.selected_dat,
			groups = 	my.groups ,
			scales = my.scale ,
			alpha = my.transparency,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' * ',
					bg = 'white',
					fg = 'white'),
			col = my.colors,
			xlab = condXName,
			main = yName,
			# TODO: Fix the layout so it produces a vertical line of plots with the correct length
			#aspect =eval(parse(text=c("nlevels(shingle(my.dat$",condXName,"))")))/2,
			#layout = c(0,eval(parse(text=c("nlevels(shingle(my.dat$",condXName,"))")))),
			key = my.key ,
			aux.env = new.env(parent = emptyenv()),
#			prepanel = function(x, y, aux.env, ...) 
#			{
#				y <- na.exclude(y)
#				x <- na.exclude(x)
#				print_debug(c("eval(heatmap_parsed) ==>",eval(heatmap_parsed) ))
#				if (!is.na(eval(heatmap_parsed)))
#				{
#					aux.env$heatmap.max <- max(aux.env$heatmap.max, eval(heatmap_parsed), na.rm = TRUE)
#				}
#				list()
#			},
#			panel = function(x, y, subscripts, aux.env, ...) 
#			{	
#				# Filter na from x and y at each panel so they are not taken in account in eval(heatmap_parsed)
#				na_x = which(!is.na(x))
#				y <- y[na_x]
#				x <- x[na_x]
#				subscripts <- subscripts[na_x]
#				na_y = which(!is.na(y))
#				y <- y[na_y]
#				x <- x[na_y]
#				subscripts <- subscripts[na_y]
#				
#				#TODO: fail gracefully with invalid statements  
#				eval_heatmap = eval(heatmap_parsed) / aux.env$heatmap.max
#				
#				# Put gray squares  if NaN
#				if (!is.na(eval_heatmap) )
#				{panel.fill(col = rgb(eval_heatmap,eval_heatmap,eval_heatmap))}
#				else
#				{panel.grid(col = "gray", lty = 1)}
#				
#				# The most important fuction responsable for drawing the lines
#				panel.superpose(x, y, subscripts, ...)
#			}
	)
	print(v)
	my.viz <<- v
}

####plot_viz_superposed_densityplot####
plot_viz_superposed_bwplot<- function( yName, groupName) 
{
	print(groupName)
	assign_colors("Set2", eval(parse(text = paste('my.selected_dat$',groupName, sep=''))))
	print_debug('1 Make syntactically valid names')
	yName = make.names(yName)
	
	print_debug('2 Extract column with names from my.selected_dat')
	y  <-  my.selected_dat[[yName]]	
	
	print_debug('3 Parse groupName and heatmap')
	if (nchar(groupName) != 0)
	{ group_parsed = parse(text = groupName)}
	else
	{ group_parsed = NULL}
	
	print_debug('3 plot_viz_superposed xyplot')	
	v =	bwplot(interaction(eval(group_parsed), X.run.number.) ~ y,
			data = my.selected_dat,
			groups = 	my.groups ,
			scales = my.scale,
			alpha = my.transparency,
			col = my.colors,
			key = 	my.key,
			aspect = "fill")
	print(v)
	my.viz <<- v
}

#############
### SPLOMS ###
#############

####plot_viz_splom####
plot_viz_splom_names<- function(checked_column_names)
{
	assign_colors("Pastel1", my.selected_dat$X.run.number.)
	print(checked_column_names)
	print(str(my.selected_dat))
	print(str(subset(my.selected_dat,select = checked_column_names)))
	v = splom(subset(my.selected_dat,select = checked_column_names),  
			pch = '.',  
			col = my.colors,
			alpha = my.transparency, 
			scale = my.scale ,  
			groups = my.selected_dat$X.run.number.
	)
	print(v)
	my.viz <<- v
	print(my.colors)
}

####plot_viz_splom####
plot_viz_splom<- function(param_heatmap_idx)
{
	assign_colors("Pastel1", my.selected_dat$X.run.number.)
	splom_dat <- my.new_dat[param_heatmap_idx:dim(my.new_dat)[2]];
	print(str(splom_dat))
	v  = splom(splom_dat,  
			pch = '.',  
			col = my.colors,
			alpha = my.transparency, 
			scale = my.scale ,  
			groups =my.new_dat$X.run.number.
	)
	print(v)
	viz <<- v
	print(my.colors)
}

####plot_viz_splom####
plot_viz_marginals<- function(checked_column_names)
{
	assign_colors("Pastel1", my.selected_dat$X.run.number.)
	print(checked_column_names)
	print(str(my.selected_dat))
	print(str(subset(my.selected_dat,select = checked_column_names)))
	v = histogram(~ X.step. ,
			data = my.selected_dat,
			pch = '.', 
			col = my.colors,
			key = 	my.key ,
			alpha = my.transparency, 
			scale = my.scale ,  
			groups = my.selected_dat$X.run.number.
	)
#	v = marginal.plot(subset(my.selected_dat,select = checked_column_names),
#									pch = '.', 
#									col = my.colors,
#									alpha = my.transparency, 
#									scale = my.scale ,  
#									groups = my.selected_dat$X.run.number.
#							)
	
	print(v)
	my.viz <<- v
	print(my.colors)
}



